<?php

namespace App\Http\Controllers\Web;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Controllers\Web\WebController;

use Session , Cookie , Config , Log , Validator;

use App\Models\StoreGoods;
use App\Models\Cart;
use App\Models\Order;

use App\Models\UserAddress;
use App\Models\OrderStatusChangeLog;
use App\Models\WxPay;
use EasyWeChat\Foundation\Application;

class OrderController extends WebController
{

    private $_length;
    public function __construct(){
        parent::__construct();
        $this->_length = 10;
        $this->_response['_title']  = '订单';
        $this->_response['_css'] = [
        ];
    }


    public function index(Request $request){
        $this->_response['_css'] = [
            'order.css'
        ];

        $this->_response['type'] = 0;
        if($request->has('type')){
            $this->_response['type'] = $request->get('type');
        }

        $this->_response['active_bottom'] = 'order';

        return view('web.order' , $this->_response);
    }

    public function getList(Request $request){
        $page = 1;
        if($request->has('page')){
            $page = $request->get('page');
        }

        $status = Config::get('order.status');

        $offset = ($page -1) * $this->_length;

        $orderModel = new Order();

        global $uid;
        $search = [
            'u_id'      => $uid,
            'status'    => [1,2,3,4,5,7]
        ];

        if($request->has('type')){
            $type = $request->get('type');
            if($type == 1){
                $search['status'] = [1];
            }elseif($type == 2){
                $search['status'] = [2 , 3];
            }elseif($type == 3){
                $search['status'] = [4];
            }
        }

        $order   = $orderModel->getOrderInfo($search , $offset , $this->_length);

        $order['pageData']['page'] = $page;

        foreach ($order['list'] as $o){
            $o->status_msg = $status[$o->status];
        }

        return response()->json(['code' => 0 , 'data' => $order]);
    }

    public function init(Request $request){
        $validation = Validator::make($request->all() , [
            'address_id'                    => 'required',
        ] , [
            'address_id.required'           => '没有收货地址',
        ]);

        if($validation->fails()){
            $error = $validation->errors()->all();
            return response()->json(['code' => -1 , 'msg' => $error[0]]);
        }
        global $uid;
        $sId = $request->session()->get('store_id_' . $uid);

        $addressId = $request->get('address_id');

        $address = UserAddress::where('id' , $addressId)->where('u_id' , $uid)->first();

        if(!$address->lng || !$address->lat){
            return response()->json(['code' => -3 , 'msg' => '获取经纬度失败，请重新获取地址' ]);
        }

        $amapStoreId = $this->getAmapStore($address->lng , $address->lat);

        if($sId != $amapStoreId){
            return response()->json(['code' => -2 , 'msg' => '所选商品不在收获地址的配送范围,请重新选择' ]);
        }

        $carts = Cart::where('s_id' , $sId)->where('u_id' , $uid)->get();

        $goods = [];
        $gNum = 0;
        foreach ($carts as $c){
            $goods[$gNum] = new \stdClass();
            $goods[$gNum]->goods_id = $c->g_id;
            $goods[$gNum]->buy_num = $c->buy_num;
            $goods[$gNum]->s_id = $sId;
            $gNum++;
        }

        $orderModel = new Order();
        $orderInitData = $orderModel->init($uid , $request->get('address_id') , $goods);

        return response()->json($orderInitData);

    }

    public function cart(Request $request){
        $this->_response['_title']  = '购物车';
        $this->_response['_css'] = [
            'cart.css'
        ];

        global $uid;

        $cartModel = new Cart();

        $sId = $request->session()->get('store_id_' . $uid);

        Log::debug("店铺ID".$sId);

        $cart   = $cartModel->getCart($uid , $sId);
        $address = UserAddress::where('u_id' , $uid)->where('useing' , 1)->whereNull('deleted_at')->first();
        if(!$address){
            $address = UserAddress::where('u_id' , $uid)->whereNull('deleted_at')->first();
        }

        $this->_response['address']             = $address;
        $this->_response['carts']               = $cart['cart'];
        $this->_response['total_price']         = $cart['total_price'];

        $differencePrice = \Config::get('order.starting_price') - $cart['total_price'];
        $this->_response['difference_price']    = $differencePrice;

        $this->_response['active_bottom'] = 'cart';

        return view('web.cart' , $this->_response);
    }

    public function updateCart(Request $request){
        $validation = Validator::make($request->all() , [
            'gid'                  => 'required',
            'buy_num'              => 'required',

        ] , [
            'gid.required'               => '没有商品',
            'buy_num.required'           => '没有购买数量',
        ]);
        if($validation->fails()){
            $error = $validation->errors()->all();
            return response()->json(['code' => -1 , 'msg' => $error[0]]);
        }

        global $uid;

        $sId = $request->session()->get('store_id_' . $uid);

        $updateData = [
            'u_id'      => $uid,
            'g_id'      => $request->get('gid'),
            's_id'      => $sId,
            'buy_num'   => $request->get('buy_num')
        ];

        $goodsData = StoreGoods::where('id' , $updateData['g_id'])->where('s_id' , $sId)->first();
        if(!$goodsData){
            return response()->json(['code' => -2 , 'msg' => '商品不存在' ]);
        }

        $updateData['now_price']    = $goodsData->now_price;

        //如果购买数量小于等于0,,则删除记录
        if($updateData['buy_num'] <= 0){
            Cart::where('u_id' , $updateData['u_id'])
                ->where('g_id' , $updateData['g_id'])
                ->delete();
            return response()->json(['code' => 0 , 'msg' => '更新购物车成功' ]);
        }else {
            Log::debug($updateData);
            $issetCart = Cart::where('u_id', $updateData['u_id'])
                ->where('g_id', $updateData['g_id'])
                ->first();
            //如果存在这条记录,则更新,否则添加
            if ($issetCart) {
                $updateData['updated_at'] = date('Y-m-d H:i:s', time());
                if (
                    Cart::where('u_id', $updateData['u_id'])
                        ->where('g_id', $updateData['g_id'])
                        ->update($updateData) === false
                ) {
                    return response()->json(['code' => -3, 'msg' => '更新购物车失败']);
                }

            } else {
                if (!Cart::create($updateData)) {
                    return response()->json(['code' => -4, 'msg' => '更新购物车失败']);
                }
            }
            return response()->json(['code' => 0 , 'msg' => '更新购物车成功' ]);
        }

    }

    public function clearCart(){
        global $uid;
        if(Cart::where('u_id' , $uid)->delete()){
            return response()->json(['code' => 0]);
        }else{
            return response()->json(['code' => 0]);
        }
    }

    public function comfirm($orderId){
        $this->_response['_title']  = '确认订单';
        $this->_response['_css'][] = 'comfirm.css';

        $orderModel = new Order();
        $this->_response['order']   = $orderModel->getOrderInfo(['ids' => [$orderId]] , 0 , 1);

        if(count($this->_response['order']['list']) == 1){
            $this->_response['order'] = $this->_response['order']['list'][0];
        }

        return view('web.comfirm' , $this->_response);
    }

    public function info($orderId){
        $this->_response['_title']  = '订单详情';
        $this->_response['_css'][] = 'comfirm.css';

        $orderModel = new Order();
        $order   = $orderModel->getOrderInfo(['ids' => [$orderId]] , 0 , 1);

        $statusLog = OrderStatusChangeLog::where('o_id' , $orderId)->orderBy('created_at' , 'desc')->get();

        $this->_response['order'] = 0;
        $this->_response['status_log'] = [];
        if(count($order['list']) == 1){
            $this->_response['order'] = $order['list'][0];

            $status = Config::get('order.status');
            foreach ($statusLog as &$sl){
                $sl->status_msg = $status[$sl->status];
            }

            $this->_response['status_log'] = $statusLog;
        }

        return view('web.order-info' , $this->_response);
    }

    public function getCartNum(Request $request){
        global $uid;

        $sId = $request->session()->get('store_id_' . $uid);

        $cartNum = Cart::where('u_id' , $uid)->where('s_id' , $sId)->count();

        return response()->json(['code' => 0 , 'data' => $cartNum]);
    }

    public function cancelOrder($orderId){
        $status = 6;
        $orderModel = new Order();
        global $uid;

        $order = Order::where('u_id' , $uid)->where('id' , $orderId)->first();
        if(!$order){
            return response()->json(['code' => -2 , 'msg' => "没有该订单"]);
        }

        if(in_array($order->status , [3,4,5,6,7,8])){
            return response()->json(['code' => -3 , 'msg' => "目前订单状态显示可不取消"]);
        }

        if($order->status == 2){
            $wxPayInfo = WxPay::where('oid', $orderId)->first();
            if (!$wxPayInfo) {
                return response()->json(['code' => -3, 'msg' => '订单不存在']);
            }

            $app = new Application(Config::get('wechat'));

            Log::debug(Config::get('wechat'));

            $refundNo = md5($order->order_num . 'refund');
            $result = $app->payment->refund($wxPayInfo->out_trade_no, $refundNo, 100);

            if ($result->return_code == 'SUCCESS') {
                if (WxPay::where('oid', $orderId)->update(['refund_no' => $refundNo]) === false) {
                    \Log::error('退款更新WxPay失败----order-id---' . $orderId);
                }

                if(!$orderModel->changeStatus($orderId , $status)){
                    \Log::error('退款更新order status失败----order-id---' . $orderId);
                }

                return response()->json(['code' => 0, 'msg' => '申请成功']);
            } else {
                \Log::error($result);
                return response()->json(['code' => -4, 'msg' => '申请失败']);
            }
        }elseif($order->status == 1){
            if($orderModel->changeStatus($orderId , $status)){
                return response()->json(['code' => 0, 'msg' => '取消成功']);
            }else{
                return response()->json(['code' => -6, 'msg' => '取消失败']);
            }
        }
    }


    public function evaluate($orderId , Request $request){
        $this->_response['_title']  = '订单详情';
        $this->_response['_css'][] = 'comfirm.css';

        $orderModel = new Order();
        $order   = $orderModel->getOrderInfo(['ids' => [$orderId]] , 0 , 1);

        $statusLog = OrderStatusChangeLog::where('o_id' , $orderId)->orderBy('created_at' , 'desc')->get();

        $this->_response['order'] = [];
        $this->_response['status_log'] = [];
        if(count($order['list']) == 1){
            $this->_response['order'] = $order['list'][0];

            $status = Config::get('order.status');
            foreach ($statusLog as &$sl){
                $sl->status_msg = $status[$sl->status];
            }

            $this->_response['status_log'] = $statusLog;
        }

        return view('web.evaluate' , $this->_response);
    }
}
